<template>
  <view class="product-detail" :style="{'--primary-color': primaryColor}">
    <!-- 页面加载状态 -->
    <PageLoading :show="pageLoading" :primary-color="primaryColor" loading-text="加载中..." />
    
    <!-- 分享按钮 - 已注释，使用微信自带分享功能 -->
    <!-- <view class="share-button" @click="shareProduct" v-show="shouldShowContent">
      <view class="share-icon">
        <text class="share-icon-text">📤</text>
      </view>
    </view> -->
    
    <!-- 页面主要内容 -->
    <view class="page-content" v-show="shouldShowContent">
    <!-- 加载状态 -->
    <view class="loading-container" v-if="isLoading">
      <view class="loading-content">
        <text class="loading-text">商品信息加载中...</text>
      </view>
    </view>
    
    <!-- 商品内容 -->
    <view class="product-content" v-else>
    <!-- 商品图片轮播 -->
    <view class="product-gallery">
      <swiper 
        class="gallery-swiper" 
        :indicator-dots="true" 
        :autoplay="false" 
        :interval="3000" 
        :duration="500"
        indicator-color="rgba(255,255,255,0.5)"
        :indicator-active-color="primaryColor"
        @change="onSwiperChange"
      >
        <swiper-item v-for="(image, index) in product.images" :key="index">
          <image 
            class="product-image" 
            :src="image.url || image" 
            mode="scaleToFill"
            @click="previewImage(index)"
          ></image>
        </swiper-item>
      </swiper>
      
      <!-- 图片指示器 -->
      <view class="gallery-indicator">
        <text class="indicator-text">{{ currentImageIndex + 1 }}/{{ product.images.length }}</text>
      </view>
      
      <!-- 商品标签 -->
      <view class="product-badges">
        <view class="badge new-badge" v-if="product.isNew">
          <text class="badge-text">新品</text>
        </view>
        <view class="badge hot-badge" v-if="product.isHot">
          <text class="badge-text">热销</text>
        </view>
        <view class="badge recommend-badge" v-if="product.isRecommend">
          <text class="badge-text">推荐</text>
        </view>
      </view>
    </view>

    <!-- 商品基本信息 -->
    <view class="product-info">
      <view class="product-title">
        <text class="title-text">{{ product.name }}</text>
      </view>
      
      <!-- 价格区域 -->
      <view class="price-section">
        <view class="price-row">
          <text class="current-price">¥{{ product.price }}</text>
          <text class="original-price" v-if="product.originalPrice && product.originalPrice > product.price">¥{{ product.originalPrice }}</text>
        </view>
        
        <!-- 销量和评价 -->
        <view class="stats-row">
          <text class="stats-text">已售{{ product.sales }}件</text>
          <text class="stats-divider">|</text>
          <text class="stats-text">{{ product.views }}人浏览</text>
          <text class="stats-divider">|</text>
          <text class="stats-text">{{ product.comments || 0 }}条评价</text>
        </view>
      </view>
    </view>
    
    <!-- 商品详细信息 -->
     <view class="product-details" :style="{boxShadow: themeColorStyles.detailsShadow, border: themeColorStyles.detailsBorder}">
       <view class="detail-row">
         <text class="detail-label">商品分类：</text>
         <text class="detail-value">{{ product.category }}</text>
       </view>
       
       <view class="detail-row">
         <text class="detail-label">商品品牌：</text>
         <text class="detail-value">{{ product.brand }}</text>
       </view>
       
       <view class="detail-row">
         <text class="detail-label">商品单位：</text>
         <text class="detail-value">{{ product.unit }}</text>
       </view>
       
       <view class="detail-row">
         <text class="detail-label">商品重量：</text>
         <text class="detail-value">{{ product.weight }}kg</text>
       </view>
       
       <view class="detail-row">
         <text class="detail-label">商品体积：</text>
         <text class="detail-value">{{ product.volume }}cm³</text>
       </view>
       
       <view class="detail-row">
         <text class="detail-label">库存数量：</text>
         <text class="detail-value">{{ product.stock }}{{ product.unit }}</text>
       </view>
       
       <view class="detail-row" v-if="product.keywords">
         <text class="detail-label">关键词：</text>
         <text class="detail-value">{{ product.keywords }}</text>
       </view>
     </view>

    <!-- 商品类型选择 -->
    <view class="spec-section" v-if="product.skuList && product.skuList.length > 0">
      <view class="spec-header">
        <text class="spec-title">选择商品类型</text>
      </view>
      
      <view class="spec-item">
        <view class="spec-options">
          <view 
            class="spec-option"
            :class="{active: selectedSku && selectedSku.skuId === sku.skuId}"
            v-for="sku in product.skuList" 
            :key="sku.skuId"
            @click="selectSku(sku)"
          >
            <image 
              class="spec-option-image" 
              :src="getSkuImageUrl(sku.image)" 
              mode="aspectFill"
              v-if="sku.image"
            ></image>
            <view class="spec-option-info">
              <text class="spec-option-text">{{ sku.skuName }}</text>
              <text class="spec-price-text">¥{{ sku.price }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- SKU规格信息卡片 -->
    <view class="sku-spec-section" v-if="selectedSku && selectedSku.specInfo">
      <view class="spec-header">
        <text class="spec-title">商品规格</text>
      </view>
      
      <view class="sku-spec-content">
        <view class="sku-spec-item" v-for="(spec, index) in getSkuSpecifications()" :key="index">
          <text class="sku-spec-label">{{ spec.name }}：</text>
          <text class="sku-spec-value">{{ spec.value }}</text>
        </view>
      </view>
    </view>

    <!-- 数量选择 -->
    <view class="quantity-section">
      <text class="quantity-label">购买数量</text>
      <view class="quantity-control">
        <view class="quantity-btn" @click="decreaseQuantity">
          <text class="quantity-btn-text">-</text>
        </view>
        <input class="quantity-input" v-model="quantity" type="number" />
        <view class="quantity-btn" @click="increaseQuantity">
          <text class="quantity-btn-text">+</text>
        </view>
      </view>
    </view>

    <!-- 商品详情 -->
    <view class="detail-section">
      <view class="detail-header">
        <text class="detail-title">商品详情</text>
      </view>
      
      <view class="detail-content">
        <!-- 富文本商品描述 -->
        <view class="detail-description">
          <rich-text class="rich-content" :nodes="product.richDescription" v-if="Array.isArray(product.richDescription)"></rich-text>
          <rich-text class="html-content" :nodes="product.richDescription" v-else></rich-text>
        </view>
      </view>
    </view>

    <!-- 用户评论 -->
    <view class="comment-section">
      <view class="comment-header">
        <text class="comment-title">用户评价 ({{ product.comments }})</text>
        <view class="comment-rating">
          <view class="rating-stars">
            <text class="star" v-for="i in 5" :key="i" :class="{active: i <= product.rating}">★</text>
          </view>
          <text class="rating-text">{{ product.rating }}.0</text>
        </view>
      </view>
      
      <view class="comment-list">
        <!-- 有评价时显示评价列表（只显示前3条） -->
        <template v-if="product.commentList.length > 0">
          <view class="comment-item" v-for="(comment, index) in product.commentList.slice(0, 3)" :key="index" @click="goToCommentDetail(comment)">
          <view class="comment-user">
            <view class="user-info">
              <text class="user-name">{{ comment.userName }}</text>
              <view class="comment-rating-small">
                <text class="star-small" v-for="i in 5" :key="i" :class="{active: i <= comment.rating}">★</text>
              </view>
            </view>
            <text class="comment-time">{{ comment.createTime }}</text>
          </view>
          
          <view class="comment-content">
            <text class="comment-text comment-text-ellipsis">{{ comment.content }}</text>
          </view>
          
          <view class="comment-images" v-if="comment.images && comment.images.length > 0">
            <image 
              class="comment-image" 
              v-for="(img, imgIndex) in comment.images.slice(0, 3)" 
              :key="imgIndex"
              :src="img" 
              mode="aspectFill"
              @click="previewCommentImage(comment.images, imgIndex)"
            ></image>
            <view class="more-images" v-if="comment.images.length > 3" @click="goToCommentDetail(comment)">
              <text class="more-images-text">+{{ comment.images.length - 3 }}</text>
            </view>
          </view>
          
          <!-- 商家回复 -->
          <view class="merchant-reply" v-if="comment.reply">
            <view class="reply-header">
              <text class="reply-label">商家回复：</text>
            </view>
            <text class="reply-content">{{ comment.reply }}</text>
          </view>
        </view>
        </template>
        
        <!-- 无评价时显示提示 -->
        <view class="no-comment" v-if="product.commentList.length === 0">
          <text class="no-comment-text">暂无评价，快来抢沙发吧~</text>
        </view>
      </view>
      
      <view class="comment-more" @click="viewAllComments">
        <text class="more-text">查看全部评价 ({{ product.comments }})</text>
        <text class="more-arrow">></text>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-actions" 
          :style="{
            '--primary-color': primaryColor,
            borderTop: `1rpx solid rgba(${hexToRgb(primaryColor).r}, ${hexToRgb(primaryColor).g}, ${hexToRgb(primaryColor).b}, 0.08)`,
            boxShadow: `0 -4rpx 20rpx rgba(${hexToRgb(primaryColor).r}, ${hexToRgb(primaryColor).g}, ${hexToRgb(primaryColor).b}, 0.06)`
          }">
      <view class="action-buttons">
        <view class="action-btn add-cart-btn" 
              :class="{disabled: !canPurchase}"
              :style="{background: canPurchase ? themeColorStyles.addCartBtnBg : '#cccccc', boxShadow: canPurchase ? themeColorStyles.addCartBtnShadow : 'none', border: canPurchase ? themeColorStyles.addCartBtnBorder : '1rpx solid #cccccc'}" 
              @click="addToCart">
          <text class="action-btn-text" :style="{color: canPurchase ? '#fff' : '#999'}">{{ canPurchase ? '加入购物车' : (purchaseRestrictionMessage || '暂无SKU信息') }}</text>
        </view>
        <view class="action-btn buy-now-btn" 
              :class="{disabled: !canPurchase}"
              :style="{background: canPurchase ? themeColorStyles.buyNowBtnBg : '#cccccc', boxShadow: canPurchase ? themeColorStyles.buyNowBtnShadow : 'none'}" 
              @click="buyNow">
          <text class="action-btn-text" :style="{color: canPurchase ? '#fff' : '#999'}">{{ canPurchase ? '立即购买' : (purchaseRestrictionMessage || '暂无SKU信息') }}</text>
        </view>
      </view>
    </view>

    <!-- 购买确认弹窗 -->
    <view class="confirm-modal" v-if="showConfirmModal" @click="closeConfirmModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">确认购买信息</text>
          <text class="modal-close" @click="closeConfirmModal">×</text>
        </view>
        
        <view class="modal-body">
          <view class="product-summary">
            <image class="summary-image" :src="product.images[0]" mode="aspectFill"></image>
            <view class="summary-info">
              <text class="summary-name">{{ product.name }}</text>
              <text class="summary-price">¥{{ product.price }}</text>
            </view>
          </view>
          
          <view class="confirm-item">
            <text class="confirm-label">商品分类：</text>
            <text class="confirm-value">{{ product.category }}</text>
          </view>
          
          <view class="confirm-item">
            <text class="confirm-label">选择类型：</text>
            <text class="confirm-value">{{ selectedSku ? selectedSku.skuName : selectedStyle }}</text>
          </view>
          
          <view class="confirm-item" v-if="selectedSku">
            <text class="confirm-label">SKU价格：</text>
            <text class="confirm-value">¥{{ selectedSku.price }}</text>
          </view>
          
          <view class="confirm-item" v-if="selectedSku && selectedSku.stock">
            <text class="confirm-label">SKU库存：</text>
            <text class="confirm-value">{{ selectedSku.stock }}{{ product.unit }}</text>
          </view>
          
          <!-- SKU规格信息 -->
          <view class="confirm-specs" v-if="selectedSku && selectedSku.specInfo">
            <text class="confirm-specs-title">商品规格：</text>
            <view class="confirm-specs-content" 
                  :style="{background: themeColorStyles.specContentBg, border: themeColorStyles.specContentBorder}">
              <view class="confirm-spec-item" v-for="(spec, index) in getSkuSpecifications()" :key="index">
                <text class="confirm-spec-text">{{ spec.name }}: {{ spec.value }}</text>
              </view>
            </view>
          </view>
          
          <view class="confirm-item">
            <text class="confirm-label">购买数量：</text>
            <text class="confirm-value">{{ quantity }}{{ product.unit }}</text>
          </view>
          
          <view class="confirm-item">
            <text class="confirm-label">商品重量：</text>
            <text class="confirm-value">{{ product.weight }}kg</text>
          </view>
          
          <view class="confirm-item">
            <text class="confirm-label">商品体积：</text>
            <text class="confirm-value">{{ product.volume }}cm³</text>
          </view>
          
          <view class="confirm-item total-price">
            <text class="confirm-label">总价：</text>
            <text class="confirm-value price-highlight">¥{{ (product.price * quantity).toFixed(2) }}</text>
          </view>
        </view>
        
        <view class="modal-footer">
          <view class="modal-btn cancel-btn" 
                :style="{background: themeColorStyles.cancelBtnBg, border: themeColorStyles.cancelBtnBorder, color: themeColorStyles.primaryColor}" 
                @click="closeConfirmModal">
            <text class="btn-text" :style="{color: themeColorStyles.primaryColor}">取消</text>
          </view>
          <view class="modal-btn confirm-btn" 
                :style="{background: themeColorStyles.confirmBtnBg, boxShadow: themeColorStyles.confirmBtnShadow}" 
                @click="confirmAction">
            <text class="btn-text">{{ actionType === 'cart' ? '确认加入购物车' : '确认立即购买' }}</text>
          </view>
        </view>
      </view>
    </view>
    </view> <!-- 商品内容结束 -->
    </view>
  </view>
</template>

<script>
import { getProduct, getMobileProductDetail } from '@/api/product'
import { getCategory } from '@/api/category'
import { getBrand } from '@/api/brand'
import { addCart, getUserCartList } from '@/api/cart'
import { getCommentsByProductId } from '@/api/comment'
import { createOrder, getUserOrder } from '@/api/order'

import { API_CONFIG } from '@/api/config.js'
import cartCache from '@/utils/cartCache'
import browseTracker from '@/utils/browseTracker'
import { getToken, getUserInfo } from '@/utils/auth'
import { checkLoginStatus, handleApiError } from '@/utils/loginCheck'
import { getThemeColorFromGlobal, getThemePrimaryColor } from '@/utils/themeUtils'
import PageLoading from '@/components/PageLoading/index.vue'
import pageLoadingMixin from '@/mixins/pageLoading.js'

export default {
  components: {
    PageLoading
  },
  mixins: [pageLoadingMixin],
  data() {
    return {
      productId: '', // 商品ID
      currentImageIndex: 0,
      selectedStyle: '',
      selectedSku: null, // 选中的SKU
      quantity: 1,

      cartCount: 0,
      showConfirmModal: false,
      actionType: '', // 'cart' 或 'buy'
      isLoading: true,
      themeColor: '1', // 默认主题色
      product: {
        id: '',
        code: '',
        name: '',
        category: '',
        brand: '',
        price: 0,
        originalPrice: 0,
        costPrice: 0,
        stock: 0,
        lowStock: 0,
        unit: '',
        weight: 0,
        volume: 0,
        sales: 0,
        views: 0,
        comments: 0,
        rating: 0,
        keywords: '',
        description: '',
        isNew: false,
        isHot: false,
        isRecommend: false,
        images: [],
        richDescription: [],
        styles: [],
        skuList: [],
        commentList: []
      }
    }
  },
  async onLoad(options) {
    // 开始页面加载
    this.startPageLoading()
    
    try {
      // 初始化主题色
      await this.initThemeColor()
      this.markThemeLoaded()
      
      // 页面加载时立即更新购物车数量和角标
      await this.updateCartCount()
      this.updateTabBarBadge()
      
      if (options.id) {
        this.productId = options.id // 设置商品ID
        await this.loadProduct(options.id)
      }
      
      // 检查是否通过分享链接进入
      if (options.shared === '1') {
        // 用户通过分享链接进入商品详情页
        // 可以在这里添加分享统计逻辑
        this.recordShareVisit(options.id);
      }
      
      // 标记数据已加载
      this.markDataLoaded()
    } catch (error) {
      // console.error('商品详情页面加载失败:', error)
      this.forceCompletePageLoading()
    }
  },
  onShow() {
    // 页面显示时更新购物车数量
    this.updateCartCount().then(() => {
      // 更新完购物车数量后更新角标
      this.updateTabBarBadge()
    })
    
    // 恢复浏览时长记录
    browseTracker.resume()
  },
  
  onHide() {
    // 页面隐藏时暂停浏览时长记录
    browseTracker.pause()
  },
  
  onUnload() {
    // 页面卸载时停止浏览时长记录
    browseTracker.stopTracking()
  },
  
  // 分享给朋友
  onShareAppMessage(res) {
    // 触发分享给朋友
    
    const shareTitle = this.product.name || '精选商品';
    const shareImageUrl = this.product.images && this.product.images.length > 0 
      ? (this.product.images[0].url || this.product.images[0]) 
      : '';
    const sharePrice = this.product.price || 0;
    
    return {
      title: `${shareTitle} - ¥${sharePrice}`,
      path: `pages/product/detail?id=${this.productId}&shared=1`,
      imageUrl: shareImageUrl
    };
  },
  
  // 分享到朋友圈
  onShareTimeline() {
    // 触发分享到朋友圈
    
    const shareTitle = this.product.name || '精选商品';
    const shareImageUrl = this.product.images && this.product.images.length > 0 
      ? (this.product.images[0].url || this.product.images[0]) 
      : '';
    const sharePrice = this.product.price || 0;
    
    return {
      title: `${shareTitle} - ¥${sharePrice}`,
      query: `id=${this.productId}&shared=1`,
      imageUrl: shareImageUrl
    };
  },
  computed: {
    // 动态主题色
    primaryColor() {
      return getThemePrimaryColor(this.themeColor)
    },
    // 是否已登录（优先根据token判断，其次根据store中的昵称/用户名）
    isLoggedIn() {
      const u = this.$store.state.user || {}
      return !!u.token || !!u.nickName || !!u.name
    },
    
    // 主题色样式
    themeColorStyles() {
      return this.setThemeColorVariables(this.primaryColor)
    },
    
    // 检查商品是否有有效的SKU信息
    hasValidSku() {
      return this.product && this.product.skuList && this.product.skuList.length > 0
    },
    
    // 检查用户是否有购买权限
    canPurchase() {
      // 如果没有有效的SKU，不能购买
      if (!this.hasValidSku) {
        return false
      }
      
      // 获取当前选中的SKU
      const currentSku = this.selectedSku
      if (!currentSku) {
        return false
      }
      
      // 检查库存数量
      if (!currentSku.stock || currentSku.stock <= 0) {
        return false
      }
      
      // 使用驼峰命名格式的字段（后端返回的是驼峰格式）
      const isVipBuy = currentSku.isVipBuy
      const buyWhiteList = currentSku.buyWhiteList
      
      // 获取用户信息
      const userRoles = this.$store.state.user.roles || []
      
      // 获取当前登录用户的ID
      let userId = null
      try {
        // 优先从storage_data中获取userId
        const storageData = uni.getStorageSync('storage_data') || {}
        userId = storageData['userId'] || ''
        
        // 如果storage_data中没有，尝试从store中获取
        if (!userId) {
          userId = this.$store.state.user.id
        }
        
        // 如果还是没有，尝试从uni.getStorageSync直接获取
        if (!userId) {
          userId = uni.getStorageSync('userId')
        }
        
      } catch (error) {
        console.error('获取用户ID失败:', error)
        return false
      }
      
      // 优先级1：检查白名单权限（如果白名单不为空）
      if (buyWhiteList && buyWhiteList.trim() !== '') {
        // 如果没有用户ID，不允许购买
        if (!userId || userId === 'default' || userId === '') {
          return false
        }
        
        // 将白名单字符串按逗号分割成数组
        const whiteList = buyWhiteList.split(',').map(id => id.trim())
        
        // 检查当前用户ID是否在白名单中
        const isInWhiteList = whiteList.includes(String(userId))
        
        // 白名单不为空时，只看是否在白名单中，与会员无关
        if (isInWhiteList) {
          return true
        } else {
          return false
        }
      }
      
      // 优先级2：白名单为空时，检查会员权限
      if (isVipBuy === 1) {
        // 检查用户是否有会员角色（role_id=5对应的角色）
        const hasVipRole = userRoles.some(role => {
          // 这里需要根据实际的角色标识来判断
          // 如果角色存储的是role_id，则直接比较
          // 如果存储的是role_key，则需要对应会员的role_key
          return role === '5' || role === 'vip' || role === 'member'
        })
        
        if (!hasVipRole) {
          return false
        } else {
          return true
        }
      }
      
      // 优先级3：白名单为空且没有开启会员开关，人人都可以购买
      return true
    },
    
    // 获取购买限制提示信息
    purchaseRestrictionMessage() {
      if (!this.hasValidSku) {
        return '商品暂时无法购买'
      }
      
      const currentSku = this.selectedSku
      if (!currentSku) {
        return '请选择商品规格'
      }
      
      // 如果可以购买，返回空字符串
      if (this.canPurchase) {
        return ''
      }
      
      // 检查库存数量
      if (!currentSku.stock || currentSku.stock <= 0) {
        return '商品库存已经没有了'
      }
      
      // 获取用户信息
      const userRoles = this.$store.state.user.roles || []
      
      // 获取当前登录用户的ID
      let userId = null
      try {
        // 优先从storage_data中获取userId
        const storageData = uni.getStorageSync('storage_data') || {}
        userId = storageData['userId'] || ''
        
        // 如果storage_data中没有，尝试从store中获取
        if (!userId) {
          userId = this.$store.state.user.id
        }
        
        // 如果还是没有，尝试从uni.getStorageSync直接获取
        if (!userId) {
          userId = uni.getStorageSync('userId')
        }
      } catch (error) {
        console.error('获取用户ID失败:', error)
      }
      
      // 使用驼峰命名格式的字段（后端返回的是驼峰格式）
      const isVipBuy = currentSku.isVipBuy
      const buyWhiteList = currentSku.buyWhiteList
      
      // 优先级1：检查白名单权限（如果白名单不为空）
      if (buyWhiteList && buyWhiteList.trim() !== '') {
        // 如果没有用户ID，提示登录
        if (!userId || userId === 'default' || userId === '') {
          return '请先登录后购买'
        }
        
        // 将白名单字符串按逗号分割成数组
        const whiteList = buyWhiteList.split(',').map(id => id.trim())
        
        // 检查当前用户ID是否在白名单中
        if (!whiteList.includes(String(userId))) {
          return '您暂无购买此商品的权限'
        }
        
        // 如果在白名单中，不会到这里，因为canPurchase会返回true
        return ''
      }
      
      // 优先级2：白名单为空时，检查会员权限
      if (isVipBuy === 1) {
        const hasVipRole = userRoles.some(role => {
          return role === '5' || role === 'vip' || role === 'member'
        })
        
        if (!hasVipRole) {
          return '此商品仅限会员购买'
        }
        
        // 如果是会员，不会到这里，因为canPurchase会返回true
        return ''
      }
      
      // 优先级3：白名单为空且没有开启会员开关，人人都可以购买
      // 如果到这里说明有其他问题
      return '商品暂时无法购买'
    }
  },
  methods: {
    // 分享商品
    shareProduct() {
      // 点击分享按钮
      
      // 构建分享内容
      const shareTitle = this.product.name || '精选商品';
      const sharePrice = this.product.price || 0;
      
      // 分享信息
      const shareInfo = {
        title: shareTitle,
        price: sharePrice,
        productId: this.productId
      };
      
      // 在小程序中，直接显示分享选项
      this.showShareModal();
    },
    
    // 显示分享弹窗
    showShareModal() {
      // 在小程序中，显示分享提示
      uni.showModal({
        title: '分享商品',
        content: '点击右上角菜单按钮，选择"转发"即可分享给朋友或群聊',
        showCancel: false,
        confirmText: '知道了',
        success: (res) => {
          // 用户确认分享提示
        }
      });
    },
    

    
    // 记录分享访问统计
    recordShareVisit(productId) {
      try {
        // 记录分享访问统计
        
        // 这里可以调用后端API记录分享访问统计
        // 例如：
        // this.$http.post('/api/share/visit', {
        //   productId: productId,
        //   visitTime: new Date().toISOString(),
        //   source: 'share_link'
        // });
        
        // 暂时只记录到控制台
        // 分享访问统计已记录
      } catch (error) {
        // console.error('记录分享访问统计失败:', error);
      }
    },
    
    // 初始化主题色
    async initThemeColor() {
      try {
        // 获取主题色配置
        const themeColor = await getThemeColorFromGlobal()
        
        // 判断是否为异步主题色（数字字符串表示需要从服务器获取）
        if (/^\d+$/.test(themeColor)) {
          // 异步获取主题色
          this.themeColor = themeColor
          // 异步获取主题色
        } else {
          // 同步获取主题色（直接使用颜色值）
          this.themeColor = themeColor
          // 同步获取主题色
        }
      } catch (error) {
        // console.error('商品详情页面主题色初始化失败:', error)
        // 使用默认主题色
        this.themeColor = '1'
      }
    },
    
    // 设置主题色变量
    setThemeColorVariables(color) {
      const rgb = this.hexToRgb(color)
      
      return {
        primaryColor: color,
        addCartBtnBg: color,
        addCartBtnShadow: `0 4rpx 16rpx rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.3)`,
        addCartBtnBorder: `2rpx solid ${color}`,
        buyNowBtnBg: `linear-gradient(135deg, ${color} 0%, ${this.darkenColor(color, 20)} 100%)`,
        buyNowBtnShadow: `0 6rpx 20rpx rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.4)`,
        confirmBtnBg: `linear-gradient(135deg, ${color} 0%, ${this.darkenColor(color, 20)} 100%)`,
        confirmBtnShadow: `0 4rpx 16rpx rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.3)`,
        cancelBtnBg: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`,
        cancelBtnBorder: `2rpx solid rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.3)`,
        specContentBg: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.05)`,
        specContentBorder: `2rpx solid rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.2)`,
        detailsShadow: `0 4rpx 20rpx rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`,
        detailsBorder: `2rpx solid rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.15)`
      }
    },
    
    // 十六进制颜色转RGB
    hexToRgb(hex) {
      const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
      return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
      } : { r: 74, g: 144, b: 226 }
    },
    
    // 颜色变暗
    darkenColor(color, percent) {
      const rgb = this.hexToRgb(color)
      const factor = (100 - percent) / 100
      const r = Math.round(rgb.r * factor)
      const g = Math.round(rgb.g * factor)
      const b = Math.round(rgb.b * factor)
      return `rgb(${r}, ${g}, ${b})`
    },
    
    async loadProduct(id) {
      try {
        this.isLoading = true
        // 使用新的移动端商品详情接口，包含SKU信息
        const response = await getMobileProductDetail(id)
        
        if (response.code === 200 && response.data) {
          const productData = response.data.product
          const skuList = response.data.skuList || []
          

          
          // 检查发布状态，如果为0则不显示
          if (productData.publishStatus === 0 || productData.publishStatus === '0') {
            this.$modal.showToast('商品未发布或已下架')
            uni.navigateBack()
            return
          }
          
          // 获取分类名称
          const categoryName = await this.getCategoryName(productData.categoryId)
          
          // 获取品牌名称
          const brandName = await this.getBrandName(productData.brandId)
          
          // 更新商品基本信息
          this.product = {
            ...this.product,
            id: productData.productId,
            code: productData.productCode || '',
            name: productData.productName || '',
            category: categoryName,
            brand: brandName,
            price: parseFloat(productData.price || 0),
            originalPrice: parseFloat(productData.originalPrice || 0),
            costPrice: parseFloat(productData.costPrice || 0),
            stock: parseInt(productData.stock || 0),
            lowStock: parseInt(productData.lowStock || 0),
            unit: productData.unit || '件',
            weight: parseFloat(productData.weight || 0),
            volume: parseFloat(productData.volume || 0),
            sales: parseInt(productData.saleCount || 0),
            views: parseInt(productData.viewCount || 0),
            comments: parseInt(productData.commentCount || 0),
            keywords: productData.keywords || '',
            description: productData.description || '',
            // 商品标签
            isNew: productData.isNew === 'Y' || productData.isNew === '1' || productData.isNew === 1,
            isHot: productData.isHot === 'Y' || productData.isHot === '1' || productData.isHot === 1,
            isRecommend: productData.isRecommend === 'Y' || productData.isRecommend === '1' || productData.isRecommend === 1,
            // 商品图片
            images: this.parseProductImages(productData.mainImage),
            // 富文本描述
            richDescription: this.parseRichDescription(productData.description),
            // 商品规格（使用品牌作为款式）
            styles: [brandName || '默认'],
            // 商品SKU列表
            skuList: skuList,
            // 商品评论列表（初始为空，后续动态加载）
            commentList: [],
            // 评分（初始为0，后续根据评价计算）
            rating: 0
          }
          
          // 设置默认选中的SKU
          if (this.product.skuList && this.product.skuList.length > 0) {
            this.selectedSku = this.product.skuList[0]
            this.selectedStyle = this.selectedSku.skuName
            // 更新商品价格为选中SKU的价格
            this.product.price = parseFloat(this.selectedSku.price || 0)
            
          } else if (this.product.styles && this.product.styles.length > 0) {
            this.selectedStyle = this.product.styles[0]
          }
          
          // 商品数据加载完成
          
          // 动态加载商品评价数据
          await this.loadProductComments(this.product.id)
          
          // 商品数据加载完成后，开始记录浏览时长
          await this.startBrowseTracking()
        } else {
          this.$modal.showToast('商品信息加载失败')
        }
      } catch (error) {
        // console.error('加载商品详情失败:', error)
        await handleApiError(error)
        this.$modal.showToast('商品信息加载失败')
      } finally {
        this.isLoading = false
      }
    },
    
    // 动态加载商品评价数据
    async loadProductComments(productId) {
      try {
        // 开始加载商品评价
        const response = await getCommentsByProductId(productId)
        
        if (response.code === 200 && response.data) {
          const commentList = response.data || []
          // 获取到的评价数据
          
          // 处理评价数据
          this.product.commentList = await this.processCommentList(commentList)
          this.product.comments = commentList.length
          
          // 计算平均评分
          if (commentList.length > 0) {
            const totalRating = commentList.reduce((sum, comment) => sum + (comment.star || 5), 0)
            this.product.rating = Math.round(totalRating / commentList.length)
          } else {
            this.product.rating = 0
          }
          
          // 缓存原始评价数据供评价列表页面使用（包括空数组）
          const productCacheKey = `comment_detail_${productId}`
          uni.setStorageSync(productCacheKey, commentList)
          // 缓存评价数据
        } else {
          // 获取商品评价失败
          this.product.commentList = []
          this.product.comments = 0
          this.product.rating = 0
        }
      } catch (error) {
        // console.error('加载商品评价失败:', error)
        // console.error('错误详情:', error.message || error.toString())
        this.product.commentList = []
        this.product.comments = 0
        this.product.rating = 0
      }
    },
    
    // 获取分类名称
    async getCategoryName(categoryId) {
      if (!categoryId) return '未分类'
      
      try {
        const response = await getCategory(categoryId)
        if (response.code === 200 && response.data) {
          return response.data.categoryName || '未分类'
        }
      } catch (error) {
        // console.error('获取分类信息失败:', error)
      }
      return '未分类'
    },
    
    // 处理评论列表数据
    async processCommentList(commentList) {
      if (!commentList || !Array.isArray(commentList)) {
        return []
      }
      
      const processedComments = []
      
      for (const comment of commentList) {
        // 处理评论图片
        let images = []
        const imageData = comment.images || comment.images
        if (imageData) {
          if (Array.isArray(imageData)) {
            images = imageData.map(img => this.processImageUrl(img)).filter(img => img)
          } else if (typeof imageData === 'string') {
            images = imageData.split(',').map(img => {
              return this.processImageUrl(img.trim())
            }).filter(img => img)
          }
        }
        
        // 转换字段名称（数据库下划线命名转为前端驼峰命名）
        processedComments.push({
          id: comment.comment_id || comment.commentId || comment.id,
          productId: comment.product_id || comment.productId,
          orderId: comment.order_id || comment.orderId,
          userId: comment.user_id || comment.userId,
          userName: comment.user_name || comment.userName || '匿名用户',
          userAvatar: comment.user_avatar || comment.userAvatar || '/static/images/default-avatar.png',
          rating: comment.star || 5,
          content: comment.content || '',
          images: images,
          createTime: comment.create_time ? this.formatDate(comment.create_time) : (comment.createTime ? this.formatDate(comment.createTime) : ''),
          reply: comment.reply_content || comment.replyContent || comment.merchantReply || '',
          replyTime: comment.reply_time || comment.replyTime,
          showStatus: comment.show_status || comment.showStatus
        })
      }
      
      return processedComments
    },
    

    
    // 处理图片URL
    processImageUrl(imagePath) {
      if (!imagePath) return ''
      
      // 如果已经是完整的URL，直接返回
      if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
        return imagePath
      }
      
      // 处理服务器路径
      let serverUrl = API_CONFIG.SERVER_IP
      
      // 如果包含/dev-api，替换成/
      if (imagePath.includes('/dev-api')) {
        imagePath = imagePath.replace('/dev-api', '')
      }
      
      // 确保路径以/开头
      if (!imagePath.startsWith('/')) {
        imagePath = '/' + imagePath
      }
      
      return serverUrl + imagePath
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      const now = new Date()
      const diff = now - date
      
      // 如果是今天
      if (diff < 24 * 60 * 60 * 1000 && date.getDate() === now.getDate()) {
        return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
      }
      // 如果是昨天
      else if (diff < 48 * 60 * 60 * 1000) {
        return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
      }
      // 其他情况显示日期
      else {
        return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })
      }
    },
    
    // 获取品牌名称
    async getBrandName(brandId) {
      if (!brandId) return '默认品牌'
      
      try {
        const response = await getBrand(brandId)
        if (response.code === 200 && response.data) {
          return response.data.brandName || '默认品牌'
        }
      } catch (error) {
        // console.error('获取品牌信息失败:', error)
      }
      return '默认品牌'
    },
    
    // 解析商品图片
    parseProductImages(imagesStr) {
      if (!imagesStr) {
        return ['/static/images/default-product.png']
      }
      
      let imageList = []
      
      try {
        // 如果是JSON字符串，尝试解析
        if (typeof imagesStr === 'string' && imagesStr.startsWith('[')) {
          imageList = JSON.parse(imagesStr)
        }
        // 如果是逗号分隔的字符串
        else if (typeof imagesStr === 'string' && imagesStr.includes(',')) {
          imageList = imagesStr.split(',').map(img => img.trim()).filter(img => img)
        }
        // 如果是单个图片URL
        else if (typeof imagesStr === 'string') {
          imageList = [imagesStr]
        }
        // 如果已经是数组
        else if (Array.isArray(imagesStr)) {
          imageList = imagesStr
        }
        
        // 直接使用图片URL，不需要拼接服务器地址（七牛云存储）
        return imageList.map(img => {
          if (typeof img === 'string') {
            return img
          }
          return img
        })
      } catch (error) {
        // console.error('解析商品图片失败:', error)
      }
      
      // 默认图片
      return ['https://images.unsplash.com/photo-1549298916-b41d501d3772?w=600&h=600&fit=crop']
    },
    
    // 解析富文本描述
    parseRichDescription(detailStr) {
      if (!detailStr) {
        return [{
          name: 'div',
          attrs: { style: 'padding: 20rpx; line-height: 1.6; color: #475569; font-size: 28rpx;' },
          children: [{ type: 'text', text: '暂无详细描述' }]
        }]
      }
      
      try {
        // 如果是JSON字符串，尝试解析
        if (typeof detailStr === 'string' && (detailStr.startsWith('[') || detailStr.startsWith('{'))) {
          const parsedData = JSON.parse(detailStr)
          // 递归处理JSON数据中的图片URL
          return this.processRichTextNodes(parsedData)
        }
      } catch (error) {
        // console.error('解析富文本描述失败:', error)
      }
      
      // 如果是HTML富文本字符串，处理图片URL和样式并直接返回HTML
      if (typeof detailStr === 'string' && (detailStr.includes('<') && detailStr.includes('>'))) {
        // 处理富文本中的图片URL和样式
        let processedHtml = detailStr.replace(/<img([^>]*)>/g, (match, attrs) => {
          // 处理src属性
          let newAttrs = attrs.replace(/src="([^"]*)"/g, (srcMatch, src) => {
            if (src) {
              // 如果包含/dev-api，替换为/
              if (src.includes('/dev-api')) {
                src = src.replace('/dev-api', '')
              }
              // 七牛云存储，直接使用完整URL，不需要拼接IP地址前缀
              // 移除/profile/路径的处理
            }
            return srcMatch
          })
          
          // 添加或更新style属性
          const imageStyle = 'max-width: 100%; height: auto; border-radius: 8rpx; margin: 10rpx 0;'
          if (newAttrs.includes('style=')) {
            // 如果已有style属性，追加样式
            newAttrs = newAttrs.replace(/style="([^"]*)"/g, (styleMatch, existingStyle) => {
              return `style="${existingStyle}; ${imageStyle}"`
            })
          } else {
            // 如果没有style属性，添加样式
            newAttrs += ` style="${imageStyle}"`
          }
          
          return `<img${newAttrs}>`
        })
        return processedHtml
      }
      
      // 如果是普通文本，转换为富文本格式
      return [{
        name: 'div',
        attrs: { style: 'padding: 20rpx; line-height: 1.6; color: #475569; font-size: 28rpx;' },
        children: [{ type: 'text', text: detailStr }]
      }]
    },
    
    // 递归处理富文本节点中的图片URL
    processRichTextNodes(nodes) {
      if (!nodes) return nodes
      
      if (Array.isArray(nodes)) {
        return nodes.map(node => this.processRichTextNodes(node))
      }
      
      if (typeof nodes === 'object' && nodes !== null) {
        const processedNode = { ...nodes }
        
        // 处理img标签的src属性和样式
        if (processedNode.name === 'img' && processedNode.attrs) {
          // 处理图片URL
          if (processedNode.attrs.src) {
            let src = processedNode.attrs.src
            // 如果包含/dev-api，替换为/
            if (src.includes('/dev-api')) {
              src = src.replace('/dev-api', '')
            }
            // 七牛云存储，直接使用完整URL，不需要拼接IP地址前缀
            processedNode.attrs.src = src
          }
          
          // 添加图片自适应样式
          const existingStyle = processedNode.attrs.style || ''
          const imageStyle = 'max-width: 100%; height: auto; border-radius: 8rpx; margin: 10rpx 0;'
          processedNode.attrs.style = existingStyle ? `${existingStyle}; ${imageStyle}` : imageStyle
        }
        
        // 递归处理子节点
        if (processedNode.children) {
          processedNode.children = this.processRichTextNodes(processedNode.children)
        }
        
        return processedNode
      }
      
      return nodes
    },
    
    // 解析商品规格
    parseProductStyles(specsStr) {
      if (!specsStr) {
        return ['默认']
      }
      
      try {
        // 如果是JSON字符串，尝试解析
        if (typeof specsStr === 'string' && specsStr.startsWith('[')) {
          return JSON.parse(specsStr)
        }
        // 如果是逗号分隔的字符串
        if (typeof specsStr === 'string' && specsStr.includes(',')) {
          return specsStr.split(',').map(spec => spec.trim()).filter(spec => spec)
        }
        // 如果是单个规格
        if (typeof specsStr === 'string') {
          return [specsStr]
        }
        // 如果已经是数组
        if (Array.isArray(specsStr)) {
          return specsStr
        }
      } catch (error) {
        // console.error('解析商品规格失败:', error)
      }
      
      return ['默认']
    },
    
    onSwiperChange(e) {
      this.currentImageIndex = e.detail.current
    },
    previewImage(index) {
      uni.previewImage({
        current: index,
        urls: this.product.images
      })
    },
    selectStyle(style) {
      this.selectedStyle = style
    },
    selectSku(sku) {
      this.selectedSku = sku
      this.selectedStyle = sku.skuName
      // 更新商品价格和库存
      this.product.price = parseFloat(sku.price || 0)
      this.product.stock = parseInt(sku.stock || 0)
      // 如果当前数量超过新SKU的库存，调整数量
      if (this.quantity > this.product.stock) {
        this.quantity = Math.max(1, this.product.stock)
      }
      // console.log('=== 选中SKU ===', sku)
        // console.log('=== SKU规格信息 ===', sku.specInfo)
    },
    
    // 获取SKU图片URL
    getSkuImageUrl(imageUrl) {
      if (!imageUrl) {
        return '/static/images/default-product.png'
      }
      
      let processedUrl = imageUrl
      
      // 处理/dev-api前缀
      if (processedUrl.includes('/dev-api')) {
        processedUrl = processedUrl.replace('/dev-api', '')
      }
      
      // 七牛云存储，直接使用完整URL，不需要拼接服务器地址
      // 移除/profile/路径的处理
      
      return processedUrl
    },
    
    // 获取SKU规格信息
    getSkuSpecifications() {
      if (!this.selectedSku || !this.selectedSku.specInfo) {
        return []
      }
      
      try {
        let specs = []
        
        // 如果specInfo是JSON字符串，解析它
        if (typeof this.selectedSku.specInfo === 'string') {
          const parsedSpecs = JSON.parse(this.selectedSku.specInfo)
          // 如果解析后是对象，转换为数组格式
          if (typeof parsedSpecs === 'object' && !Array.isArray(parsedSpecs)) {
            specs = Object.keys(parsedSpecs).map(key => ({
              name: key,
              value: parsedSpecs[key]
            }))
          } else if (Array.isArray(parsedSpecs)) {
            specs = parsedSpecs
          }
        } else if (Array.isArray(this.selectedSku.specInfo)) {
          specs = this.selectedSku.specInfo
        } else if (typeof this.selectedSku.specInfo === 'object') {
          // 如果是对象，转换为数组格式
          specs = Object.keys(this.selectedSku.specInfo).map(key => ({
            name: key,
            value: this.selectedSku.specInfo[key]
          }))
        }
        
        // console.log('=== 解析后的规格信息 ===', specs)
        return specs
      } catch (error) {
        // console.error('解析SKU规格信息失败:', error)
        return []
      }
    },
    decreaseQuantity() {
      if (this.quantity > 1) {
        this.quantity--
      }
    },
    increaseQuantity() {
      if (this.quantity < this.product.stock) {
        this.quantity++
      }
    },
    addToCart() {
      if (!this.canPurchase) {
        uni.showToast({
          title: this.purchaseRestrictionMessage || '该商品暂无法加入购物车',
          icon: 'none',
          duration: 2000
        })
        return
      }
      
      // 点击加入购物车按钮
      
      this.actionType = 'cart'
      this.showConfirmModal = true
      
      // 设置actionType为cart，显示确认弹窗
    },
    buyNow() {
      if (!this.canPurchase) {
        uni.showToast({
          title: this.purchaseRestrictionMessage || '该商品暂无法购买',
          icon: 'none',
          duration: 2000
        })
        return
      }
      
      // 点击立即购买按钮
      
      this.actionType = 'buy'
      this.showConfirmModal = true
      
      // 设置actionType为buy，显示确认弹窗
    },
    closeConfirmModal() {
      this.showConfirmModal = false
      this.actionType = ''
    },
    async confirmAction() {
      // 点击确认按钮
      
      if (this.actionType === 'cart') {
        // 执行加入购物车逻辑
        
        // 再次检查库存（防止在选择和确认之间库存发生变化）
        if (!this.selectedSku || !this.selectedSku.stock || this.selectedSku.stock <= 0) {
          uni.showToast({
            title: '商品库存已经没有了',
            icon: 'none',
            duration: 2000
          })
          this.closeConfirmModal()
          return
        }
        
        // 检查购买数量是否超过库存
        if (this.quantity > this.selectedSku.stock) {
          uni.showToast({
            title: `库存不足，仅剩${this.selectedSku.stock}件`,
            icon: 'none',
            duration: 2000
          })
          this.closeConfirmModal()
          return
        }
        
        try {
          // 使用统一的登录检测
          const loginResult = await checkLoginStatus()
          if (!loginResult.isLoggedIn) {
            return
          }
          const userId = loginResult.userId
          
          // 构建购物车请求数据
          const cartData = {
            userId: userId, // 添加用户ID
            productId: this.product.id,
            skuId: this.selectedSku ? this.selectedSku.skuId : null, // 传入选中的SKU ID
            quantity: this.quantity,
            orgId: parseInt(API_CONFIG.ORG_ID) // 添加组织ID
          }
          
          // 添加购物车请求数据
          
          // 调用后端接口添加到购物车
          const response = await addCart(cartData)
          // 添加购物车响应
          
          if (response.code === 200) {
             // 使用之前已经验证过的userId
             
             // 构建缓存数据项 - 只有当后端返回真实cartId时才缓存
             if (response.data?.cartId) {
               const cacheItem = {
                 cartId: response.data.cartId, // 只使用后端返回的真实ID
                 productId: this.product.id,
                 skuId: this.selectedSku ? this.selectedSku.skuId : null, // 添加SKU ID
                 productName: this.product.name,
                 productPrice: this.product.price,
                 productImage: this.product.images[0]?.url || this.product.images[0] || '',
                 skuName: this.selectedStyle,
                 quantity: this.quantity,
                 checked: 'Y'
                }
                
                // 同步到缓存
                cartCache.addToCartCache(userId, cacheItem)
              }
             
             // 设置购物车刷新标记，确保购物车页面能显示最新数据
             uni.setStorageSync('refreshCart', true)
             
             // 更新购物车计数
             await this.updateCartCount()
             
             // 更新tabbar购物车角标
             this.updateTabBarBadge()
             
             this.$modal.showToast(`已添加${this.quantity}件商品到购物车`)
           } else {
             this.$modal.showToast(response.msg || '添加购物车失败')
           }
        } catch (error) {
          // console.error('=== 添加购物车失败详细信息 ===', error)
          await handleApiError(error)
        }
      } else if (this.actionType === 'buy') {
          // 执行立即购买逻辑
        
        // 再次检查库存（防止在选择和确认之间库存发生变化）
        if (!this.selectedSku || !this.selectedSku.stock || this.selectedSku.stock <= 0) {
          uni.showToast({
            title: '商品库存已经没有了',
            icon: 'none',
            duration: 2000
          })
          this.closeConfirmModal()
          return
        }
        
        // 检查购买数量是否超过库存
        if (this.quantity > this.selectedSku.stock) {
          uni.showToast({
            title: `库存不足，仅剩${this.selectedSku.stock}件`,
            icon: 'none',
            duration: 2000
          })
          this.closeConfirmModal()
          return
        }
        
        try {
          // 使用统一的登录检测
          const loginResult = await checkLoginStatus()
          if (!loginResult.isLoggedIn) {
            return
          }
          const userId = loginResult.userId
          
          // 构建订单数据
          const orderData = {
            userId: userId,
            totalAmount: (this.product.price * this.quantity).toFixed(2),
            status: 1, // 订单状态为1（待支付）
            orgId: parseInt(API_CONFIG.ORG_ID), // 添加组织ID
            items: [{
              productId: this.product.id,
              skuId: this.selectedSku ? this.selectedSku.skuId : null,
              productName: this.product.name,
              productPrice: this.product.price,
              quantity: this.quantity,
              subtotal: (this.product.price * this.quantity).toFixed(2)
            }]
          }
          
          // 创建订单请求数据
          
          // 调用创建订单接口
          const response = await createOrder(orderData)
          // 创建订单响应
          
          if (response.code === 200 && response.data) {
            this.$modal.showToast('订单创建成功')
            
            // 跳转到订单详情页面 - 使用订单号参数
            // 先根据订单ID获取订单详情，然后使用订单号跳转
            const orderId = response.data.orderId || response.data.id;
            if (response.data.orderNo) {
              // 如果响应中直接包含订单号，直接使用
              uni.navigateTo({
                url: `/pages/order/detail?orderNo=${response.data.orderNo}`
              })
            } else {
              // 如果没有订单号，根据订单ID获取订单详情
              try {
                const userInfo = await getUserInfo();
                const orderDetailResponse = await getUserOrder(orderId, userInfo.userId);
                if (orderDetailResponse.code === 200 && orderDetailResponse.data && orderDetailResponse.data.orderNo) {
                  uni.navigateTo({
                    url: `/pages/order/detail?orderNo=${orderDetailResponse.data.orderNo}`
                  })
                } else {
                  this.$modal.showToast('获取订单信息失败')
                }
              } catch (error) {
                console.error('获取订单详情失败:', error);
                this.$modal.showToast('跳转失败，请重试')
              }
            }
          } else {
            this.$modal.showToast(response.msg || '订单创建失败')
          }
        } catch (error) {
          // 创建订单失败
          await handleApiError(error)
        }
      }
      this.closeConfirmModal()
    },
    previewCommentImage(images, index) {
      uni.previewImage({
        current: index,
        urls: images
      })
    },
    viewAllComments() {
      if (this.product.commentList.length === 0) {
        this.$modal.showToast('暂无评价数据')
        return
      }
      // 跳转到评价列表页面
      uni.navigateTo({
        url: `/pages/comment/list?productId=${this.product.id}&productName=${encodeURIComponent(this.product.name)}`
      })
    },
    
    // 跳转到评论详情
    goToCommentDetail(comment) {
      uni.navigateTo({
        url: `/pages/comment/detail?commentId=${comment.id}&productId=${this.product.id}`
      })
    },
    async updateCartCount() {
      try {
        const userId = this.$store.state.user.id || uni.getStorageSync('userId') || 'default'
        // 更新购物车数量
        
        // 优先从缓存获取购物车数量
        if (cartCache.isCacheValid(userId)) {
          const cachedData = cartCache.getCartCache(userId)
          if (cachedData && cachedData.length > 0) {
            this.cartCount = cachedData.reduce((total, item) => total + parseInt(item.quantity || 0), 0)
            // 从缓存更新购物车数量
            return
          }
        }
        
        // 缓存无效时从后端获取
        const response = await getUserCartList()
        if (response.code === 200) {
          const cartData = response.data || []
          this.cartCount = cartData.reduce((total, item) => total + parseInt(item.quantity || 0), 0)
          // 从后端更新购物车数量
        }
      } catch (error) {
        // 获取购物车数量失败
        // 从本地存储获取作为备用
        const localCart = uni.getStorageSync('cartList') || []
        this.cartCount = localCart.reduce((total, item) => total + parseInt(item.quantity || 0), 0)
      }
    },
    
    // 更新tabbar购物车角标
    updateTabBarBadge() {
      try {
        if (this.cartCount > 0) {
          uni.setTabBarBadge({
            index: 2, // 购物车tab的索引
            text: this.cartCount.toString()
          })
        } else {
          uni.removeTabBarBadge({
            index: 2
          })
        }
        // 更新tabbar角标
      } catch (error) {
        // 更新tabbar角标失败
      }
    },
    
    // 开始浏览时长记录
    async startBrowseTracking() {
      try {
        // 商品详情页面开始浏览记录
        
        const token = getToken()
        // Token检查
        
        if (token) {
          // 正在获取用户信息
          const userInfo = await getUserInfo()
          
          const userId = userInfo?.userId
          // 用户ID
          
          if (userId) {
            const pageInfo = {
              pageType: 'product_detail',
              pageName: '商品详情页',
              pageUrl: `/pages/product/detail?id=${this.productId}`,
              productId: this.productId,
              productName: this.product?.name || '未知商品',
              productImage: this.product?.images?.[0]?.url || this.product?.images?.[0] || '',
              productPrice: this.product?.price || 0
            }
            
            // 准备启动浏览记录
            browseTracker.startTracking(pageInfo, userId)
            // 浏览记录启动完成
          } else {
            // 无法获取用户ID，无法记录浏览时长
          }
        } else {
          // 用户未登录，无法记录浏览时长
        }
      } catch (error) {
        // 启动浏览时长记录失败
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.product-detail {
  background: #f8fafc;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

/* 商品图片轮播 */
.product-gallery {
  position: relative;
  height: 750rpx;
  background: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 20rpx color-mix(in srgb, var(--primary-color) 6%, transparent 94%);
  border: 1rpx solid color-mix(in srgb, var(--primary-color) 8%, transparent 92%);
  overflow: hidden;
  
  .gallery-swiper {
    width: 100%;
    height: 100%;
    
    .product-image {
      width: 100% !important;
      height: 100% !important;
      object-fit: fill !important;
      display: block;
    }
  }
  
  .gallery-indicator {
    position: absolute;
    bottom: 20rpx;
    right: 20rpx;
    background: rgba(0, 0, 0, 0.6);
    padding: 8rpx 16rpx;
    border-radius: 20rpx;
    
    .indicator-text {
      font-size: 24rpx;
      color: #fff;
    }
  }
  
  .product-badges {
    position: absolute;
    top: 20rpx;
    left: 20rpx;
    display: flex;
    flex-direction: column;
    gap: 10rpx;
    
    .badge {
      padding: 8rpx 16rpx;
      border-radius: 20rpx;
      
      .badge-text {
        font-size: 20rpx;
        color: #fff;
        font-weight: 600;
      }
      
      &.new-badge {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
      }
      
      &.hot-badge {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
      }
      
      &.recommend-badge {
        background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
      }
    }
  }
}

/* 商品基本信息 */
.product-info {
  background: #fff;
  padding: 30rpx;
  margin: 20rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 20rpx color-mix(in srgb, var(--primary-color) 6%, transparent 94%);
  border: 1rpx solid color-mix(in srgb, var(--primary-color) 8%, transparent 92%);
  
  .product-title {
    margin-bottom: 15rpx;
    
    .title-text {
      font-size: 36rpx;
      font-weight: 600;
      color: #1e293b;
      line-height: 1.4;
    }
  }
  
  .product-subtitle {
    margin-bottom: 25rpx;
    
    .subtitle-text {
      font-size: 28rpx;
      color: #64748b;
      line-height: 1.4;
    }
  }
  
  .price-section {
    .price-row {
      display: flex;
      align-items: center;
      margin-bottom: 15rpx;
      
      .current-price {
        font-size: 48rpx;
        font-weight: bold;
        color: var(--primary-color);
        margin-right: 20rpx;
      }
      
      .original-price {
        font-size: 28rpx;
        color: #94a3b8;
        text-decoration: line-through;
        margin-right: 15rpx;
      }
      
      .discount-tag {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        padding: 6rpx 12rpx;
        border-radius: 12rpx;
        
        .discount-text {
          font-size: 20rpx;
          color: #fff;
          font-weight: 600;
        }
      }
    }
    
    .stats-row {
      display: flex;
      align-items: center;
      
      .stats-text {
        font-size: 24rpx;
        color: #64748b;
      }
      
      .stats-divider {
        font-size: 24rpx;
        color: #cbd5e1;
        margin: 0 15rpx;
      }
    }
  }
}

/* 商品规格选择 */
.spec-section {
  background: #fff;
  padding: 35rpx;
  margin: 25rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 20rpx color-mix(in srgb, var(--primary-color) 8%, transparent 92%);
  border: 1rpx solid color-mix(in srgb, var(--primary-color) 10%, transparent 90%);
  
  .spec-item {
    display: flex;
    align-items: flex-start;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f1f5f9;
    
    &:last-child {
      border-bottom: none;
    }
    
    .spec-label {
      width: 120rpx;
      font-size: 28rpx;
      color: #475569;
      font-weight: 500;
    }
    
    .spec-value {
      flex: 1;
      font-size: 28rpx;
      color: #1e293b;
    }
    
    .spec-options {
      flex: 1;
      display: flex;
      flex-wrap: wrap;
      gap: 15rpx;
      
      .spec-option {
          padding: 25rpx;
          border: 2rpx solid #e2e8f0;
          border-radius: 12rpx;
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          display: flex;
          flex-direction: row;
          align-items: center;
          min-width: 220rpx;
          max-width: 100%;
          flex-wrap: wrap;
          margin-bottom: 18rpx;
          
          &.active {
            border-color: var(--primary-color);
            background: color-mix(in srgb, var(--primary-color) 8%, transparent 92%);
            box-shadow: 0 2rpx 8rpx color-mix(in srgb, var(--primary-color) 12%, transparent 88%);
          }
          
          &:active {
            transform: scale(0.95);
          }
        
        .spec-option-image {
          width: 80rpx;
          height: 80rpx;
          border-radius: 8rpx;
          margin-right: 25rpx;
          flex-shrink: 0;
        }
        
        .spec-option-info {
          display: flex;
          flex-direction: column;
          flex: 1;
          min-width: 0;
          justify-content: center;
        }
        
        .spec-option-text {
          font-size: 26rpx;
          color: #475569;
          margin-bottom: 10rpx;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          max-width: 100%;
          line-height: 1.3;
        }
        
        .spec-price-text {
          font-size: 24rpx;
          color: var(--primary-color);
          font-weight: 600;
        }
      }
    }
  }
}

/* SKU规格信息卡片 */
.sku-spec-section {
  background: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 20rpx color-mix(in srgb, var(--primary-color) 8%, transparent 92%);
  border: 1rpx solid color-mix(in srgb, var(--primary-color) 10%, transparent 90%);
  overflow: hidden;
  
  .spec-header {
    padding: 30rpx 30rpx 20rpx;
    border-bottom: 1rpx solid #f1f5f9;
    
    .spec-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #1e293b;
    }
  }
  
  .sku-spec-content {
    padding: 20rpx 30rpx 30rpx;
    
    .sku-spec-item {
      display: flex;
      align-items: center;
      padding: 12rpx 0;
      border-bottom: 1rpx solid #f8fafc;
      
      &:last-child {
        border-bottom: none;
      }
      
      .sku-spec-label {
        font-size: 28rpx;
        color: #64748b;
        font-weight: 500;
        min-width: 120rpx;
      }
      
      .sku-spec-value {
        font-size: 28rpx;
        color: #1e293b;
        flex: 1;
      }
    }
  }
}

/* 数量选择 */
.quantity-section {
  background: #fff;
  padding: 30rpx;
  margin: 20rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 20rpx color-mix(in srgb, var(--primary-color) 8%, transparent 92%);
  border: 1rpx solid color-mix(in srgb, var(--primary-color) 10%, transparent 90%);
  display: flex;
  align-items: center;
  justify-content: space-between;
  
  .quantity-label {
    font-size: 28rpx;
    color: #475569;
    font-weight: 500;
  }
  
  .quantity-control {
    display: flex;
    align-items: center;
    border: 2rpx solid color-mix(in srgb, var(--primary-color) 15%, transparent 85%);
    border-radius: 12rpx;
    overflow: hidden;
    
    .quantity-btn {
      width: 80rpx;
      height: 60rpx;
      background: color-mix(in srgb, var(--primary-color) 5%, transparent 95%);
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.3s ease;
      
      &:active {
        background: color-mix(in srgb, var(--primary-color) 10%, transparent 90%);
      }
      
      .quantity-btn-text {
        font-size: 32rpx;
        color: var(--primary-color);
        font-weight: 600;
      }
    }
    
    .quantity-input {
      width: 120rpx;
      height: 60rpx;
      text-align: center;
      font-size: 28rpx;
      color: #1e293b;
      border: none;
      background: #fff;
    }
  }
}

/* 商品详情 */
.detail-section {
  background: #fff;
  padding: 30rpx;
  margin: 20rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 20rpx color-mix(in srgb, var(--primary-color) 8%, transparent 92%);
  border: 1rpx solid color-mix(in srgb, var(--primary-color) 10%, transparent 90%);
  
  .detail-header {
    margin-bottom: 25rpx;
    
    .detail-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #1e293b;
    }
  }
  
  .detail-content {
    .detail-item {
      display: flex;
      margin-bottom: 20rpx;
      
      .detail-label {
        font-size: 26rpx;
        color: #64748b;
        margin-right: 10rpx;
      }
      
      .detail-value {
        font-size: 26rpx;
        color: #1e293b;
        flex: 1;
      }
    }
    
    .detail-description {
      .rich-content {
        line-height: 1.6;
        
        ::v-deep img {
          max-width: 100%;
          height: auto;
          border-radius: 8rpx;
          margin: 10rpx 0;
        }
        
        ::v-deep p {
          margin: 10rpx 0;
          color: #475569;
          font-size: 28rpx;
        }
        
        ::v-deep h1, ::v-deep h2, ::v-deep h3, ::v-deep h4, ::v-deep h5, ::v-deep h6 {
          color: #1e293b;
          margin: 20rpx 0 10rpx;
          font-weight: 600;
        }
      }
      
      .html-content {
        line-height: 1.6;
        
        ::v-deep img {
          max-width: 100%;
          height: auto;
          border-radius: 8rpx;
          margin: 10rpx 0;
        }
        
        ::v-deep p {
          margin: 10rpx 0;
          color: #475569;
          font-size: 28rpx;
        }
        
        ::v-deep h1, ::v-deep h2, ::v-deep h3, ::v-deep h4, ::v-deep h5, ::v-deep h6 {
          color: #1e293b;
          margin: 20rpx 0 10rpx;
          font-weight: 600;
        }
      }
    }
  }
}

/* 用户评论 */
.comment-section {
  background: #fff;
  padding: 30rpx;
  margin: 20rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 20rpx color-mix(in srgb, var(--primary-color) 8%, transparent 92%);
  border: 1rpx solid color-mix(in srgb, var(--primary-color) 10%, transparent 90%);
  
  .comment-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    
    .comment-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #1e293b;
    }
    
    .comment-rating {
      display: flex;
      align-items: center;
      
      .rating-stars {
        display: flex;
        margin-right: 10rpx;
        
        .star {
          font-size: 28rpx;
          color: #e2e8f0;
          
          &.active {
            color: #fbbf24;
          }
        }
      }
      
      .rating-text {
        font-size: 26rpx;
        color: #64748b;
      }
    }
  }
  
  .comment-list {
    .comment-item {
      padding: 25rpx 0;
      border-bottom: 1rpx solid #f1f5f9;
      
      &:last-child {
        border-bottom: none;
      }
      
      .comment-user {
        display: flex;
        align-items: center;
        margin-bottom: 15rpx;
        
        .user-info {
          flex: 1;
          
          .user-name {
            font-size: 26rpx;
            color: #1e293b;
            font-weight: 500;
            display: block;
            margin-bottom: 5rpx;
          }
          
          .comment-rating-small {
            display: flex;
            
            .star-small {
              font-size: 20rpx;
              color: #e2e8f0;
              
              &.active {
                color: #fbbf24;
              }
            }
          }
        }
        
        .comment-time {
          font-size: 22rpx;
          color: #94a3b8;
        }
      }
      
      .comment-content {
        margin-bottom: 15rpx;
        
        .comment-text {
          font-size: 28rpx;
          color: #475569;
          line-height: 1.5;
        }
        
        .comment-text-ellipsis {
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
      
      .comment-images {
        display: flex;
        gap: 10rpx;
        margin-bottom: 15rpx;
        
        .comment-image {
          width: 120rpx;
          height: 120rpx;
          border-radius: 8rpx;
        }
        
        .more-images {
          width: 120rpx;
          height: 120rpx;
          border-radius: 8rpx;
          background-color: rgba(0, 0, 0, 0.6);
          display: flex;
          align-items: center;
          justify-content: center;
          
          .more-images-text {
            color: #ffffff;
            font-size: 24rpx;
            font-weight: 500;
          }
        }
      }
      
      .merchant-reply {
        background: color-mix(in srgb, var(--primary-color) 4%, transparent 96%);
        padding: 20rpx;
        border-radius: 12rpx;
        border-left: 4rpx solid var(--primary-color);
        border: 1rpx solid color-mix(in srgb, var(--primary-color) 8%, transparent 92%);
        
        .reply-header {
          margin-bottom: 8rpx;
          
          .reply-label {
            font-size: 24rpx;
            color: var(--primary-color);
            font-weight: 600;
          }
        }
        
        .reply-content {
          font-size: 26rpx;
          color: #475569;
          line-height: 1.4;
        }
      }
    }
    
    .no-comment {
      text-align: center;
      padding: 60rpx 0;
      
      .no-comment-text {
        font-size: 28rpx;
        color: #94a3b8;
        line-height: 1.5;
      }
    }
  }
  
  .comment-more {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20rpx 0;
    margin-top: 20rpx;
    border-top: 1rpx solid #f1f5f9;
    
    .more-text {
      font-size: 26rpx;
      color: var(--primary-color);
      margin-right: 8rpx;
    }
    
    .more-arrow {
      font-size: 24rpx;
      color: var(--primary-color);
    }
  }
}

/* 底部操作栏 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 20rpx 30rpx;
  // 边框和阴影通过动态绑定设置
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  
  .action-buttons {
    flex: 1;
    display: flex;
    gap: 20rpx;
    
    .action-btn {
      flex: 1;
      height: 80rpx;
      border-radius: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.3s ease;
      
      &:active {
        transform: scale(0.95);
      }
      
      &.disabled {
        cursor: not-allowed;
        opacity: 0.6;
        
        &:active {
          transform: none;
        }
      }
      
      .action-btn-text {
        font-size: 28rpx;
        font-weight: 600;
      }
      
      &.add-cart-btn {
        .action-btn-text {
          color: #fff;
        }
      }
      
      &.buy-now-btn {
        
        .action-btn-text {
          color: #fff;
        }
      }
    }
  }
}

/* 购买确认弹窗样式 */
.confirm-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  
  .modal-content {
    background: #fff;
    border-radius: 20rpx;
    width: 90%;
    max-width: 600rpx;
    max-height: 80vh;
    overflow: hidden;
    animation: modalSlideIn 0.3s ease-out;
    box-shadow: 0 8rpx 40rpx color-mix(in srgb, var(--primary-color) 12%, transparent 88%);
    border: 1rpx solid color-mix(in srgb, var(--primary-color) 8%, transparent 92%);
  }
  
  .modal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 30rpx;
    border-bottom: 1px solid #f0f0f0;
    
    .modal-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
    
    .modal-close {
      font-size: 40rpx;
      color: #999;
      width: 40rpx;
      height: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  
  .modal-body {
    padding: 30rpx;
    max-height: 60vh;
    overflow-y: auto;
    
    .product-summary {
      display: flex;
      align-items: center;
      margin-bottom: 30rpx;
      padding: 20rpx;
      background: color-mix(in srgb, var(--primary-color) 4%, transparent 96%);
       border-radius: 12rpx;
       border: 1rpx solid color-mix(in srgb, var(--primary-color) 8%, transparent 92%);
      
      .summary-image {
        width: 100rpx;
        height: 100rpx;
        border-radius: 8rpx;
        margin-right: 20rpx;
      }
      
      .summary-info {
        flex: 1;
        
        .summary-name {
          display: block;
          font-size: 28rpx;
          font-weight: 500;
          color: #333;
          margin-bottom: 10rpx;
        }
        
        .summary-price {
          font-size: 32rpx;
          font-weight: 600;
          color: #ff6b35;
        }
      }
    }
    
    .confirm-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 20rpx 0;
      border-bottom: 1px solid #f5f5f5;
      
      &:last-child {
        border-bottom: none;
      }
      
      &.total-price {
        margin-top: 20rpx;
        padding-top: 30rpx;
        border-top: 2px solid #f0f0f0;
        border-bottom: none;
      }
      
      .confirm-label {
        font-size: 28rpx;
        color: #666;
        font-weight: 500;
      }
      
      .confirm-value {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        
        &.price-highlight {
          font-size: 32rpx;
          font-weight: 600;
          color: #ff6b35;
        }
      }
    }
    
    .confirm-specs {
      padding: 20rpx 0;
      border-bottom: 1px solid #f5f5f5;
      
      .confirm-specs-title {
        font-size: 28rpx;
        color: #666;
        font-weight: 500;
        margin-bottom: 15rpx;
        display: block;
      }
      
      .confirm-specs-content {
        background: color-mix(in srgb, var(--primary-color) 3%, transparent 97%);
        border-radius: 12rpx;
        padding: 20rpx;
        border: 1rpx solid color-mix(in srgb, var(--primary-color) 10%, transparent 90%);
        
        .confirm-spec-item {
          margin-bottom: 12rpx;
          padding: 8rpx 0;
          border-bottom: 1rpx solid #f1f5f9;
          
          &:last-child {
            margin-bottom: 0;
            border-bottom: none;
          }
          
          .confirm-spec-text {
            font-size: 26rpx;
            color: #64748b;
            line-height: 1.5;
            font-weight: 400;
          }
        }
      }
    }
  }
  
  .modal-footer {
    display: flex;
    padding: 30rpx;
    gap: 20rpx;
    border-top: 1px solid #f0f0f0;
    
    .modal-btn {
      flex: 1;
      height: 80rpx;
      border-radius: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .btn-text {
        font-size: 28rpx;
        font-weight: 500;
      }
      
      &.cancel-btn {
        .btn-text {
          // 颜色通过动态绑定设置
        }
      }
      
      &.confirm-btn {
        .btn-text {
          color: #fff;
        }
      }
    }
  }
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-50rpx) scale(0.9);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

/* 商品详细信息样式 */
.product-details {
  background: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
  // 阴影和边框通过动态绑定设置
  
  .detail-row {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1px solid #f5f5f5;
    
    &:last-child {
      border-bottom: none;
    }
    
    .detail-label {
      font-size: 28rpx;
      color: #666;
      font-weight: 500;
      min-width: 160rpx;
    }
    
    .detail-value {
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
      flex: 1;
    }
  }
}

/* 加载状态样式 */
.loading-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #666;
  text-align: center;
}

/* 分享按钮样式 */
.share-button {
  position: fixed;
  top: 100rpx;
  right: 30rpx;
  z-index: 1000;
  width: 80rpx;
  height: 80rpx;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10rpx);
  border: 1rpx solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.95);
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.15);
  }
  
  .share-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    
    .share-icon-text {
      font-size: 32rpx;
      color: #333;
      font-weight: 500;
    }
  }
  
  /* 悬浮动画效果 */
  animation: shareButtonFloat 3s ease-in-out infinite;
}

@keyframes shareButtonFloat {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-6rpx);
  }
}

/* 在小屏幕设备上调整分享按钮位置 */
@media (max-width: 750rpx) {
  .share-button {
    top: 80rpx;
    right: 20rpx;
    width: 70rpx;
    height: 70rpx;
    
    .share-icon .share-icon-text {
      font-size: 28rpx;
    }
  }
}
</style>
